package com.webber.demo.common.utils;

import java.security.MessageDigest;
/**
 * 加密算法工具类
 * @author JobsZhang
 *
 */
public class EncoderUtil {
	private static final String MD5 = "MD5";
	private static final String SHA1 = "SHA-1";
	private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	/**
	 * 调用jdk自带加密方法
	 * 
	 * @param algorithm
	 * @param str
	 * @return String
	 */
	private static String encode(String algorithm, String str) {
		if (str == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
			messageDigest.update(str.getBytes());
			return getFormattedText(messageDigest.digest());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}
	/**
	 * 获取sha1加密后的字符串
	 * @param 加密之前的明文str
	 * @return
	 */
	public static String encodeBySha1(String str){
		return encode(SHA1, str).toLowerCase();
	}
	/**
	 * 获取md5加密后的字符串
	 * @param 要加密的明文str
	 * @return
	 */
	public static String encodeByMD5(String str) {
		if (str == null) {
			return null;
		}
		try {
			MessageDigest messageDigest = MessageDigest.getInstance(MD5);
			messageDigest.update(str.getBytes());
			return getFormattedText(messageDigest.digest()).toLowerCase();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	/**
	 * 从摘要中取出原始字节并格式化
	 * 
	 * @param bytes
	 *            
	 * @return the 格式化后的字符串
	 */
	private static String getFormattedText(byte[] bytes) {
		int len = bytes.length;
		StringBuilder buf = new StringBuilder(len * 2);
		// 把密文转换成十六进制的字符串形式
		for (int j = 0; j < len; j++) {
			buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
			buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
		}
		return buf.toString();
	}
	public static void main(String[] args) {
		String token  = "636da1ecd1254343adb75cf97ac477fc";
		String time = "1505291348000";
		String key = "9587a4b12f0d4a9b85149ecc53c78cb5";
		String userId = "be2ef7c987304c4ab25d14c5bcc1a60d";
		//41a140ebc1e26756cc929df7e290b9d0
		String encodeToken = encodeByMD5(time + token + key);
		System.out.println(encodeToken);
	}
}
